import {jwtDecode} from 'jwt-decode';
import {cookies} from 'next/headers';
import {redirect} from "next/navigation";

// 存储 Tokens 到 Cookie
export async function setAuthTokens({
                                        access_token,
                                        refresh_token,
                                    }: {
    access_token: string;
    refresh_token: string;
}) {
    (await cookies()).set('access_token', access_token, {
        httpOnly: true,
        secure: process.env.NODE_ENV === 'production',
        maxAge: 60 * 15, // 15分钟
    });
    (await cookies()).set('refresh_token', refresh_token, {
        httpOnly: true,
        secure: process.env.NODE_ENV === 'production',
        maxAge: 60 * 60 * 24 * 7, // 7天
    });
}

// 获取 Tokens
export async function getAuthTokens() {
    return {
        accessToken: (await cookies()).get('access_token')?.value,
        refreshToken: (await cookies()).get('refresh_token')?.value,
    };
}

// 清除Token
export async function clearAuthTokens() {
    (await cookies()).delete("access_token");
    (await cookies()).delete("refresh_token");
}


export async function checkAuth() {
    let accessToken = (await cookies()).get('access_token')?.value
    const refreshToken = (await cookies()).get('refresh_token')?.value

    // 1. 无token直接跳转
    if (!accessToken || !refreshToken) redirect('/login')

    // 2. 检查access token是否过期
    try {
        const {exp} = jwtDecode(accessToken)
        if (exp * 1000 < Date.now()) {
            // 尝试刷新token
            const res = await fetch('http://localhost:8000/auth/refresh', {
                method: 'POST',
                headers: {'Authorization': `Bearer ${refreshToken}`}
            })
            if (!res.ok) {
                throw Error()
            }
            accessToken = (await res.json()).access_token
            (await cookies()).set('access_token', accessToken)
        }
    } catch {
        await clearAuthTokens();
        redirect('/login')
    }
}